//
//  TJWithdrawalController.m
//  Teleport
//
//  Created by hc-101 on 2020/6/18.
//  Copyright © 2020 xtjun. All rights reserved.
//

#import "TJWithdrawalController.h"
#import "TJTopUpRecordController.h"
#import "TJScanController.h"
#import "TJWithdrawalAlertView.h"
#import "TJSettingMoneyPasswordController.h"
#import "TJSelectCoinController.h"
#import "TJChainNameController.h"
@interface TJWithdrawalController ()

@property (weak, nonatomic) UITextField *numberTextField;
@property (weak, nonatomic) UITextField *userIdTextField;
@property (weak, nonatomic) UILabel *availableLabel;
@property (weak, nonatomic) UIView *freeView;
@property (weak, nonatomic) UILabel *freeValueLabel;
@property (weak, nonatomic) UILabel *arriveValueLabel;

/**重要提示 */
@property (weak, nonatomic) UILabel *tipLabel;
@property (weak, nonatomic) TJWithdrawalAlertView *withdrawalAlertView;
@property (weak, nonatomic) UIButton *determineButton;
@property (weak, nonatomic) UIButton *alertDetermineButton;
/**全部数量 */
@property (copy, nonatomic) NSString *maxNum;
/**币种BTC USDT */
@property (copy, nonatomic) NSString *coinName;

/**币种 */
@property (weak, nonatomic) UILabel *coinLabel;
/**链名称 */
@property (weak, nonatomic) UILabel *chainLabel;
/**链名称按钮 */
@property (weak, nonatomic) UIButton *chainArrowButton;

/**手续费*/
//如果等于 手续费就是trade
//如果不等于  手续费就是提币数量*trade
/**tradeType */
@property (copy, nonatomic) NSString *tradeType;
@property (copy, nonatomic) NSString *trade;


@end

@implementation TJWithdrawalController {
    dispatch_source_t _sendSMSTimer;
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    
    if (_sendSMSTimer) {
        dispatch_source_cancel(_sendSMSTimer);
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.view.backgroundColor = UIColor_Hex(0xf2f2f2);
    self.navigationBar.rightBarButton = [TJButtonBarButton barButtonWithTitle:@"提币记录".localizedString color:UIColor.whiteColor target:self action:@selector(didClickNavBarRightButton)];
    
    self.navigationBar.backgroundColor = UIColor_Hex(0x2C6CC7);
    self.navigationBar.lineView.hidden = YES;
    [self.navigationBar backBarButtonWhiteColor];
    self.navigationBar.titleTextColor = UIColor.whiteColor;
    self.coinName =@"BTC";
    
    
    self.navigationBar.title = @"提币".localizedString;
    //可提资产
    UILabel *availableLabel = [UILabel lableWithSuperView:self.view font:UIFont_Px(15) color:UIColor_Hex(0x262626) title:@"" textAlignment:NSTextAlignmentLeft];
    [availableLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(KNavBarHight);
        make.left.offset(16);
        make.height.offset(60);
    }];
    //币种
    UIView *coinNameContentView = [UIView tj_addToView:self.view];
    coinNameContentView.backgroundColor = UIColor.whiteColor;
    [coinNameContentView shearRoundedCornersWithRadiu:3];
    
    [coinNameContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(16);
        make.right.offset(-16);
        make.top.equalTo(availableLabel.mas_bottom);
        make.height.offset(44);
    }];
    
    UILabel *coinNameLabel = [UILabel lableWithSuperView:coinNameContentView font:UIFont_Px(15) color:UIColor_Hex(0x262626) title:@"币种".localizedString textAlignment:NSTextAlignmentLeft];
    [coinNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.left.offset(12);
        make.height.offset(40);
    }];
    
    UIButton *coinNameArrowButton = [UIButton tj_addToView:coinNameContentView];
    [coinNameArrowButton setImage:[UIImage imageNamed:@"cellArrowIcon"] forState:UIControlStateNormal];
    [coinNameArrowButton setImage:[UIImage imageNamed:@"cellArrowIcon"] forState:UIControlStateHighlighted];
    [coinNameArrowButton addTarget:self action:@selector(didClickCoinNameArrowButton) forControlEvents:UIControlEventTouchUpInside];
    [coinNameArrowButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    [coinNameArrowButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.right.offset(-3);
        make.height.offset(30);
        //        make.width.offset(10);
    }];
    
    
    UILabel *coinLabel = [UILabel lableWithSuperView:coinNameContentView font:UIFont_Px(15) color:UIColor.blackColor title:@"BTC".localizedString textAlignment:NSTextAlignmentCenter];
    [coinLabel addTapGesturesWithTarget:self action:@selector(didClickCoinNameArrowButton)];
    [coinLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.right.equalTo(coinNameArrowButton.mas_left).offset(-3);
        make.height.offset(30);
        //        make.width.offset(50);
    }];
    
    
    //链名称
    UIView *chainContentView = [UIView tj_addToView:self.view];
    chainContentView.backgroundColor = UIColor.whiteColor;
    [chainContentView shearRoundedCornersWithRadiu:3];
    
    [chainContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(16);
        make.right.offset(-16);
        make.top.equalTo(coinNameContentView.mas_bottom).offset(10);
        make.height.offset(44);
    }];
    
    UILabel *chainNameLabel = [UILabel lableWithSuperView:chainContentView font:UIFont_Px(15) color:UIColor_Hex(0x262626) title:@"链名称".localizedString textAlignment:NSTextAlignmentLeft];
    [chainNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.left.offset(12);
        make.height.offset(40);
    }];
    
    UIButton *chainArrowButton = [UIButton tj_addToView:chainContentView];
    [chainArrowButton setImage:[UIImage imageNamed:@"cellArrowIcon"] forState:UIControlStateNormal];
    [chainArrowButton setImage:[UIImage imageNamed:@"cellArrowIcon"] forState:UIControlStateHighlighted];
    [chainArrowButton addTarget:self action:@selector(didClickChainArrowButton) forControlEvents:UIControlEventTouchUpInside];
    [chainArrowButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    [chainArrowButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.right.offset(-3);
        make.height.offset(30);
        //        make.width.offset(10);
    }];
    chainArrowButton.hidden = YES;
    
    
    UILabel *chainLabel = [UILabel lableWithSuperView:chainContentView font:UIFont_Px(15) color:UIColor.blackColor title:@"".localizedString textAlignment:NSTextAlignmentCenter];
    [chainLabel addTapGesturesWithTarget:self action:@selector(didClickChainArrowButton)];
    [chainLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.right.equalTo(coinNameArrowButton.mas_left).offset(-3);
        make.height.offset(30);
        //        make.width.offset(50);
    }];
    UIView *chainLineView = [UIView tj_addToView:chainContentView];
    chainLineView.backgroundColor = UIColor.tj_separatorColor;
    [chainLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(12);
        make.right.offset(-12);
        make.bottom.offset(0);
        make.height.offset(1);
    }];
    
    
    
    //提币地址
    UIView *accountContentView = [UIView tj_addToView:self.view];
    accountContentView.backgroundColor = UIColor.whiteColor;
    [accountContentView shearRoundedCornersWithRadiu:3];
    
    [accountContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(16);
        make.right.offset(-16);
        make.top.equalTo(chainContentView.mas_bottom).offset(0);
        make.height.offset(44);
    }];
    
    UILabel *accountLabel = [UILabel lableWithSuperView:accountContentView font:UIFont_Px(15) color:UIColor_Hex(0x262626) title:@"提币地址".localizedString textAlignment:NSTextAlignmentLeft];
    [accountLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.left.offset(12);
        make.height.offset(40);
    }];
    
    
    UIView *accountLineView = [UIView tj_addToView:accountContentView];
    accountLineView.backgroundColor = UIColor.tj_separatorColor;
    [accountLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(12);
        make.right.offset(-12);
        make.bottom.offset(0);
        make.height.offset(1);
    }];
    
    [accountLabel setContentHuggingPriority:(UILayoutPriorityRequired) forAxis:(UILayoutConstraintAxisHorizontal)];
    
    UITextField *userIdTextField = [UITextField tj_addToView:accountContentView];
    userIdTextField.placeholder = @"请输入地址".localizedString;
    userIdTextField.font = UIFont_Px(15);
    userIdTextField.keyboardType = UIKeyboardTypeNamePhonePad;
    [userIdTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(accountLabel.mas_right).offset(3);
        make.centerY.offset(0);
        make.height.offset(34);
        make.right.offset(-46);
    }];
    
    UIButton *scanButton = [UIButton tj_addToView:accountContentView];
    [scanButton setImage:[UIImage imageNamed:@"small_scan_icon"] forState:UIControlStateNormal];
    [scanButton setImage:[UIImage imageNamed:@"small_scan_icon"] forState:UIControlStateHighlighted];
    [scanButton addTarget:self action:@selector(didClickScanButton) forControlEvents:UIControlEventTouchUpInside];
    [scanButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    [scanButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(30);
        make.right.offset(-16);
        make.height.offset(30);
        make.centerY.offset(0);
    }];
    
    UIView *userIDLineView = [UIView tj_addToView:accountContentView];
    userIDLineView.backgroundColor = UIColor.tj_separatorColor;
    [userIDLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(12);
        make.right.offset(-12);
        make.bottom.offset(0);
        make.height.offset(1);
    }];
    
    
    UIView *numberContentView = [UIView tj_addToView:self.view];
    numberContentView.backgroundColor = UIColor.whiteColor;
    [numberContentView shearRoundedCornersWithRadiu:3];
    [numberContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(16);
        make.right.offset(-16);
        make.top.equalTo(accountContentView.mas_bottom).offset(0);
        make.height.offset(44);
    }];
    
    UILabel *numberLabel = [UILabel lableWithSuperView:numberContentView font:UIFont_Px(15) color:UIColor_Hex(0x262626) title:@"数量".localizedString textAlignment:NSTextAlignmentLeft];
    [numberLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.left.offset(12);
        make.height.offset(40);
    }];
    
    
    UILabel *allLabel = [UILabel lableWithSuperView:numberContentView font:UIFont_Px(15) color:UIColor_Hex(0x2C6CC8) title:@"全部".localizedString textAlignment:NSTextAlignmentCenter];
    [allLabel addTapGesturesWithTarget:self action:@selector(tapAllLabel)];
    [allLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.right.offset(0);
        make.height.offset(30);
        make.width.offset(50);
    }];
    
    //币种
    //    UILabel *unitLabel = [UILabel lableWithSuperView:numberContentView font:UIFont_Px(15) color:UIColor_Hex(0x262626) title:self.coinName textAlignment:NSTextAlignmentCenter];
    //    [unitLabel mas_makeConstraints:^(MASConstraintMaker *make) {
    //        make.centerY.offset(0);
    //        make.right.equalTo(allLabel.mas_left);
    //        make.height.offset(30);
    //        make.height.offset(50);
    //    }];
    //
    UITextField *numberTextField = [UITextField tj_addToView:numberContentView];
    numberTextField.placeholder = @"请输入数量".localizedString;
    numberTextField.font = UIFont_Px(15);
    numberTextField.keyboardType = UIKeyboardTypeDecimalPad;
    [numberTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(numberLabel.mas_right).offset(20);
        make.centerY.offset(0);
        make.height.offset(34);
        make.width.offset(120);
    }];
    
    UIView *numberLineView = [UIView tj_addToView:numberContentView];
    numberLineView.backgroundColor = UIColor.tj_separatorColor;
    [numberLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(12);
        make.right.offset(-12);
        make.bottom.offset(0);
        make.height.offset(1);
    }];
    
    [numberLabel setContentCompressionResistancePriority:(UILayoutPriorityRequired) forAxis:(UILayoutConstraintAxisHorizontal)];
    //    [unitLabel setContentCompressionResistancePriority:(UILayoutPriorityRequired) forAxis:(UILayoutConstraintAxisHorizontal)];
    [allLabel setContentCompressionResistancePriority:(UILayoutPriorityRequired) forAxis:(UILayoutConstraintAxisHorizontal)];
    
    
    
    
    UIView *freeView = [UIView tj_addToView:self.view];
    [freeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(16);
        make.right.offset(-16);
        make.top.equalTo(numberContentView.mas_bottom).offset(20);
        make.height.offset(65);
    }];
    
    
    UILabel *freeLabel = [UILabel lableWithSuperView:freeView font:UIFont_Px(12) color:UIColor_Hex(0x343434) title:@"到账手续费".localizedString textAlignment:NSTextAlignmentLeft];
    [freeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(16);
        make.left.offset(12);
    }];
    
    UILabel *freeValueLabel = [UILabel lableWithSuperView:freeView font:UIFont_Px(12) color:UIColor_Hex(0x343434) title:@"" textAlignment:NSTextAlignmentLeft];
    [freeValueLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(freeLabel);
        make.right.offset(-12);
    }];
    
    
    UILabel *arriveLabel = [UILabel lableWithSuperView:freeView font:UIFont_Px(12) color:UIColor_Hex(0x343434) title:@"实际到账".localizedString textAlignment:NSTextAlignmentLeft];
    [arriveLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(freeLabel.mas_bottom).offset(16);
        make.left.offset(12);
    }];
    
    UILabel *arriveValueLabel = [UILabel lableWithSuperView:freeView font:UIFont_Px(12) color:UIColor_Hex(0x343434) title:@"" textAlignment:NSTextAlignmentLeft];
    [arriveValueLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(arriveLabel);
        make.right.equalTo(freeValueLabel);
    }];
    
    
    UIButton *tipButton = [UIButton buttonWithSuperView:self.view font:UIFont_Px(12) color:UIColor_Hex(0x666666) title:@"重要提示".localizedString];
    [tipButton setImage:[UIImage imageNamed:@"WithdrawalTipIcon"] forState:UIControlStateNormal];
    [tipButton setImage:[UIImage imageNamed:@"WithdrawalTipIcon"] forState:UIControlStateHighlighted];
    [tipButton setContentHorizontalAlignment:(UIControlContentHorizontalAlignmentLeft)];
    [tipButton setImagePosition:LXMImagePositionLeft spacing:5];
    [tipButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.offset(120);
        make.left.offset(28);
        make.top.equalTo(freeView.mas_bottom).offset(30);
        make.height.offset(20);
    }];
    
    
    UILabel *tipLabel = [UILabel lableWithSuperView:self.view font:UIFont_Px(12) color:UIColor_Hex(0x666666) title:[NSString stringWithFormat:@"1、最小提币数量为0%@\n2、提现时间为30分钟内，具体到账时间以区块链网络速度决定\n3、为了确保安全，提现时将进行人工审核，请耐心等待".localizedString, self.coinName] textAlignment:NSTextAlignmentLeft];
    tipLabel.attributedText = [tipLabel.text titleMargin:6 withAlignment:NSTextAlignmentLeft];
    tipLabel.numberOfLines = 0;
    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(tipButton.mas_bottom).offset(10);
        make.left.offset(28);
        make.right.offset(-28);
    }];
    
    UIButton *determineButton = [UIButton buttonWithSuperView:self.view font:UIFont_Px(18) color:UIColor.whiteColor title:@"确定".localizedString];
    determineButton.backgroundColor = UIColor_Hex(0x2C6CC7);
    [determineButton shearRoundedCornersWithRadiu:22];
    [determineButton addTarget:self action:@selector(didClickDetermineButton) forControlEvents:UIControlEventTouchUpInside];
    [determineButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-38);
        make.left.offset(38);
        make.height.offset(44);
        make.centerX.offset(0);
        make.bottom.offset(-TabbarSafeBottomMargin - 64);
    }];
    
    // 点击确定之后的弹框输入验证码 密码
    TJWithdrawalAlertView *withdrawalAlertView = [[TJWithdrawalAlertView alloc] initWithFrame:CGRectMake(0, KScreenHeight, KScreenWidth, 325)];
    withdrawalAlertView.backgroundColor = UIColor.whiteColor;
    _withdrawalAlertView = withdrawalAlertView;
    [self.view addSubview:withdrawalAlertView];
    /**确定按钮 */
    [withdrawalAlertView.determineButton addTarget:self action:@selector(didClickAlertDetermineButton) forControlEvents:UIControlEventTouchUpInside];
    /**发送 */
    [withdrawalAlertView.resendLabel addTapGesturesWithTarget:self action:@selector(tapResendLabel)];
    /**取消 */
    [withdrawalAlertView.cancelLabel addTapGesturesWithTarget:self action:@selector(tapCancelLabel)];
    
    
    _numberTextField = numberTextField;
    _userIdTextField = userIdTextField;
    _availableLabel = availableLabel;
    _freeView = freeView;
    _freeValueLabel = freeValueLabel;
    _arriveValueLabel = arriveValueLabel;
    _tipLabel = tipLabel;
    _determineButton = determineButton;
    _alertDetermineButton = withdrawalAlertView.determineButton;
    _coinLabel = coinLabel;
    _chainLabel = chainLabel;
    _chainArrowButton = chainArrowButton;
    
    [_numberTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [_userIdTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [_withdrawalAlertView.SMSTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [_withdrawalAlertView.passwordTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    // [self textFieldDidChange:numberTextField];
    /**获取手续费 重要提示 */
    [self loadWithdrawalRatioData:@"BTC"];
    //获取可提资产
    [self loadAvailable:@"BTC"];
    
    //默认隐藏手续费
    self.freeView.hidden = YES;
    //默认不可确定
    _determineButton.userInteractionEnabled = NO;
    _determineButton.backgroundColor = [UIColor_Hex(0x666666) colorWithAlphaComponent:0.3];
    
}
/**全部点击 */
- (void)tapAllLabel {
    _numberTextField.text = _maxNum;
    [self textFieldDidChange:_numberTextField];
}

- (void)textFieldDidChange:(UITextField *)textField {
    
    if ([_numberTextField.text doubleValue] > [self.maxNum doubleValue]) {
         [TJHud showTopAutoHideMessage:@"账户不足".localizedString];
        return;
    }
    
    if (_numberTextField.text.length) {
        
        //如果等于 手续费就是trade
        //如果不等于  手续费就是提币数量*trade
        // 实际到账 =  提币数量-手续费
        self.freeView.hidden = NO;
        self.tipLabel.hidden = NO;
        double num = [_numberTextField.text doubleValue];
        double trad;
        double fin;
        if ([self.tradeType isEqualToString:@"NUM"]) {//等于的情况
            trad = self.trade.doubleValue;
        }else{
            trad = num * self.trade.doubleValue;
        }
        fin = num - trad;
        
        
        self.freeValueLabel.text = [NSString stringWithFormat:@"到账手续费:%@%@".localizedString, [Tools reviseString: @(trad).stringValue], self.coinName];
        self.arriveValueLabel.text = [NSString stringWithFormat:@"实际到账:%@%@".localizedString, [Tools reviseString: @(fin).stringValue], self.coinName];
        
    } else {
        self.freeView.hidden = YES;
        self.tipLabel.hidden = YES;
    }
    
    
    
    _determineButton.userInteractionEnabled = _numberTextField.text.length && _userIdTextField.text.length;
    _determineButton.backgroundColor = (_determineButton.userInteractionEnabled) ? UIColor.tj_mainColor : [UIColor_Hex(0x666666) colorWithAlphaComponent:0.3];
    
    _alertDetermineButton.userInteractionEnabled = _determineButton.userInteractionEnabled && _withdrawalAlertView.SMSTextField.text.length && _withdrawalAlertView.passwordTextField.text.length;
    _alertDetermineButton.backgroundColor = (_alertDetermineButton.userInteractionEnabled) ? UIColor.tj_mainColor : [UIColor_Hex(0x666666) colorWithAlphaComponent:0.3];
}

/**确定 */
- (void)didClickDetermineButton {
    
    if (!TJUserInfo.readInfo.payPassword.replacingEmptyString.length) {
        //0，未绑定,1已绑定
        TJSettingMoneyPasswordController *settingMoneyPasswordController = [[TJSettingMoneyPasswordController alloc] init];
        [self.navigationController pushViewController:settingMoneyPasswordController animated:YES];
        return;
        
    }
    
    [UIView animateWithDuration:0.25 animations:^{
        self.withdrawalAlertView.tj_y = KScreenHeight - self.withdrawalAlertView.tj_height;
    }];
    
}
/**安全验证确定按钮点击 */
- (void)didClickAlertDetermineButton {
    
    [self.view endEditing:YES];
    
    NSString *currency = @"";
    if ([self.coinName isEqualToString:@"BTC"]) {
        currency  =self.coinName;
    }else{
        currency = [self.chainLabel.text stringByReplacingOccurrencesOfString:@"-" withString:@"/"];
 
        
    }
    
    NSDictionary *parameters = @{
        @"wallet": _userIdTextField.text,
        @"pwd": _withdrawalAlertView.passwordTextField.text,
        @"balance": _numberTextField.text,
        @"currency":currency,
        @"code": _withdrawalAlertView.SMSTextField.text,
        @"userId": TJUserInfo.readInfo.userId
    };
    
    [self showloading];
    weakify(self)
    [TJNetworking.shareNetworking POSTNew:@"member/balance/extractCoin" parameters:parameters success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
        [weakself hiddenloading];
        [TJHud showAutoHideMessage:@"提币成功".localizedString];
    
        [weakself popViewController];
    } failure:^(NSError * _Nonnull error) {
        
        [weakself hiddenloading];
        [TJHud showAutoHideMessage:error.localizedFailureReason];
    }];
    
    
    
}


/**验证码发送 */
- (void)tapResendLabel {
    
    [self.view endEditing:YES];
    
    
    NSMutableDictionary *parameters = @{}.mutableCopy;
    [parameters setObject:TJUserInfo.readInfo.phone forKey:@"phone"];
    [parameters setObject:TJUserInfo.readInfo.areaCode forKey:@"phoneCode"];
    [parameters setObject:@"WITHDRAWAL_COIN" forKey:@"type"];
    
    
    [self showloading];
    weakify(self)
    [TJNetworking.shareNetworking POSTNew:@"data/sms/sendSms" parameters:parameters success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
        
        [weakself hiddenloading];
        [TJHud showAutoHideMessage:@"发送成功".localizedString];
        
        [weakself startCountdown];
    } failure:^(NSError * _Nonnull error) {
        [weakself hiddenloading];
        [TJHud showAutoHideMessage:error.localizedFailureReason];
    }];
    
    
}
/**取消 */
- (void)tapCancelLabel {
    
    [UIView animateWithDuration:0.25 animations:^{
        self.withdrawalAlertView.tj_y = KScreenHeight;
    }];
    
}
/**倒计时 */
- (void)startCountdown {
    
    [self setSMSCodeEnable:NO];
    
    __block NSInteger timestamp = 120;
    
    dispatch_source_t sendSMSTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(0, 0));
    dispatch_source_set_timer(sendSMSTimer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(sendSMSTimer, ^{
        
        timestamp--;
        
        if (timestamp <= 0) {
            dispatch_source_cancel(sendSMSTimer);
            dispatch_async(dispatch_get_main_queue(), ^{//显示GO
                self.withdrawalAlertView.resendLabel.text = @"重新发送".localizedString;
                [self setSMSCodeEnable:YES];
            });
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                self.withdrawalAlertView.resendLabel.text = [NSString stringWithFormat:@"%lds",(long)timestamp];
                [self setSMSCodeEnable:NO];
            });
        }
    });
    _sendSMSTimer = sendSMSTimer;
    dispatch_resume(sendSMSTimer);
}


- (void)setSMSCodeEnable:(BOOL)SMSCodeEnable {
    if (SMSCodeEnable) {
        _withdrawalAlertView.resendLabel.userInteractionEnabled = YES;
        _withdrawalAlertView.SMSTextField.text = nil;
    } else {
        _withdrawalAlertView.resendLabel.userInteractionEnabled = NO;
    }
}

//选择币种点击
-(void)didClickCoinNameArrowButton {
    TJSelectCoinController *selectCoinController = [[TJSelectCoinController alloc] init];
    weakify(self)
    [selectCoinController setSelectComplete:^(NSString * _Nonnull coinName) {
        NSLog(@"name=%@", coinName);
        //输入数量清空
        weakself.numberTextField.text = nil;
        weakself.coinLabel.text = coinName;
        if ([coinName isEqualToString:@"BTC"]) {
            
            //获取重要提示 手续费
            [weakself loadWithdrawalRatioData:@"BTC"];
            
            weakself.chainArrowButton.hidden = YES;
            
            weakself.tipLabel.hidden = NO;
            
            
        }else{
            
            weakself.chainArrowButton.hidden = NO;
            //影藏重要提示
            weakself.tipLabel.hidden = YES;
            
        }
        
        //获取可提资产
        [weakself loadAvailable:coinName];
        weakself.chainLabel.text = @"";
        weakself.coinName = coinName;
        
        //隐藏手续费
        weakself.freeView.hidden = YES;
        
        [weakself textFieldDidChange:weakself.numberTextField];
        
        
        
    }];
    [self presentViewController:selectCoinController animated:NO completion:nil];
}
//链名称
- (void)didClickChainArrowButton {
    weakify(self)
    TJChainNameController *chainVC = [TJChainNameController new];
    chainVC.complete = ^(NSString * _Nonnull chainName) {
        weakself.chainLabel.text = chainName;
        /**获取手续费 重要提示 */
        [weakself loadWithdrawalRatioData:chainName];
        
        //显示重要提示
        weakself.tipLabel.hidden = NO;
    };
    chainVC.chainName = self.chainLabel.text;
    [self.navigationController pushViewController:chainVC animated:YES];
}
/**二维码点击 */
- (void)didClickScanButton {
    AVAuthorizationStatus authStatus =  [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    weakify(self)
    if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied) {
        [weakself alertWithTitle:nil message:@"不能使用相机,前往开启？".localizedString leftButtonName:@"取消".localizedString rightButtonName:@"前往开启".localizedString leftButtonBlock:nil rightButtonBlock:^{
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
        }];
        return;
    }
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (granted) {
                TJScanController *scanController = [[TJScanController alloc] init];
                [scanController setScanComplete:^(NSString * _Nonnull result) {
//                    [TJQrcodeResultHandler QrCodeResultHandlerWithController:self result:result isNeedHandle:NO complete:^(NSDictionary * _Nonnull dict) {
                    [weakself alertWithTitle:@"请确认提币地址".localizedString message:result leftButtonName:@"取消" rightButtonName:@"确定" leftButtonBlock:nil rightButtonBlock:^{
                         weakself.userIdTextField.text = result;
                    }];
                       
//                    }];
                }];
                [self presentViewController:scanController animated:YES completion:nil];
            }
        });
    }];
    
    
    
}

- (void)didClickNavBarRightButton {
    TJTopUpRecordController *topUpRecordController = [[TJTopUpRecordController alloc] init];
    //    topUpRecordController.coinNo = _coinNo;
    topUpRecordController.title = @"提币记录".localizedString;
    topUpRecordController.type = 0;
    [self.navigationController pushViewController:topUpRecordController animated:YES];
}
/**获取手续费 重要提示 */
- (void)loadWithdrawalRatioData:(NSString *)coinName {
    NSString *ID = @"";
    if ([coinName isEqualToString:@"USDT-ERC20"]) {
        ID = @"2";
    }
    if ([coinName isEqualToString:@"USDT-OMINI"]) {
        ID = @"3";
    }
    if ([coinName isEqualToString:@"BTC"]) {
        ID = @"4";
    }
    
    //id本地写死 eth id 1 usdt erc20 id 2 usdt omini id 3 btc id 4
    [TJNetworking.shareNetworking GET:@"member/balance/getWalletConfig" parameters:@{@"id":ID} success:^(NSDictionary * _Nonnull responseObject, NSDictionary *data) {
        
        NSString *tipString = [NSString stringWithFormat:@"1、最小提币数量为%@%@\n2、提现时间为30分钟内，具体到账时间以区块链网络速度决定\n3、为了确保安全，提现时将进行人工审核，请耐心等待".localizedString, data[@"minCount"], self.coinName];
        
        //重要提示
        self.tipLabel.attributedText = [tipString titleMargin:6 withAlignment:NSTextAlignmentLeft];
        
        //如果等于 手续费就是trade
        //如果不等于  手续费就是提币数量*trade
        self.tradeType = data[@"tradeType"];
        self.trade = [data[@"trade"] stringValue];
        
    } failure:^(NSError * _Nonnull error) {
        
        
    }];
    
}


//获取账户可用资产
- (void)loadAvailable:(NSString *)coinName{
    
    weakify(self)
    [TJNetworking.shareNetworking GET:@"member/balance/getBalanceList" parameters:@{@"currency":coinName,@"userId":TJUserInfo.readInfo.userId} success:^(NSDictionary * _Nonnull responseObject, NSDictionary *data) {
        NSArray *balances = data[@"balances"];
        NSDictionary *dic = balances.firstObject;
        
        weakself.availableLabel.text = [NSString stringWithFormat:@"可提资产: %@".localizedString, [dic[@"fbBalance"] stringValue]];
        weakself.maxNum = [dic[@"fbBalance"] stringValue];
    } failure:^(NSError * _Nonnull error) {
        
        [TJHud showAutoHideMessage:error.localizedFailureReason];
    }];
}

- (void)dealloc {
    if (_sendSMSTimer) {
        dispatch_source_cancel(_sendSMSTimer);
    }
}


- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

@end
